package com.bigkoo.pickerviewdemo;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerviewdemo.bean.JsonBean;
import com.google.gson.Gson;

import org.json.JSONArray;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 小嵩
 * @TODO<解析省市区数据示例>
 * @date 2017-3-16
 */
public class JsonDataActivity extends AppCompatActivity implements View.OnClickListener {


    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    public static String dbFile;
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private boolean isLoaded = false;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        Toast.makeText(JsonDataActivity.this, "开始解析数据", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
//                                initJsonData();
                                initRegionDb();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    Toast.makeText(JsonDataActivity.this, "解析数据成功", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(JsonDataActivity.this, "解析数据失败", Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json_data);
        initView();
    }

    private void initRegionDb() {
        dbFile = getExternalFilesDir("MySql") + File.separator + "grassland.db";
        int count = 0;
        long start = System.currentTimeMillis();
        Log.i("====", start + "");
        new Thread() {
            public void run() {
                InputStream is = null;//欲导入的数据库
                try {
                    is = getAssets().open("grassland.db");
                    FileOutputStream fos = new FileOutputStream(dbFile);
                    byte[] buffer = new byte[1024];
                    int count = 0;
                    while ((count = is.read(buffer)) > 0) {
                        fos.write(buffer, 0, count);
                    }
                    fos.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                SQLiteDatabase db = SQLiteDatabase.openDatabase(
                        dbFile,
                        null, SQLiteDatabase.OPEN_READONLY);
                newQuery(db);
            }
        }.start();
    }

    /**
     * 查询
     *
     * @param db
     */
    public void newQuery(SQLiteDatabase db) {
        ArrayList<JsonBean> provinceList = new ArrayList<>();//用Gson 转成实体
        options1Items = provinceList;
        Cursor cursor = db.rawQuery("select * from region where RegionId like '%0000'", null);
        // --- 遍历方式3 ---
        //for(初始条件;终止条件;每次变动的条件){}
        int count = 0;
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            String caption = cursor.getString(cursor.getColumnIndex("Caption"));
            int regionId = cursor.getInt(cursor.getColumnIndex("RegionId"));
            JsonBean provience = new JsonBean(caption, regionId);
            provinceList.add(provience);
            count++;
            Log.i("tag1", caption + "-----------------" + regionId);
        }
        if (!cursor.isClosed()) {
            cursor.close();
        }
        Log.i("tag", "--------------count==" + count);
        for (int i = 0; i < provinceList.size(); i++) {
            ArrayList<String> CityListStr = new ArrayList<>();//该省的城市列表（第二级）
            JsonBean province = provinceList.get(i);
            int region = province.getRegion();
            String s = String.valueOf(region);
            String substring = s.substring(0, 2);
            String sql1 = "select * from region where RegionId like " + "'" + substring + "%00'";
            Cursor cursor1 = db.rawQuery(sql1, null);
            for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
                String caption = cursor1.getString(cursor1.getColumnIndex("Caption"));
                int regionId = cursor1.getInt(cursor1.getColumnIndex("RegionId"));
                if (regionId != region) {
                    JsonBean.CityBean cityBean = new JsonBean.CityBean(caption, regionId);
                    List<JsonBean.CityBean> city = province.getCity();
                    if (city == null) {
                        List<JsonBean.CityBean> cityBeen = new ArrayList<>();
                        province.setCity(cityBeen);
                    }
                    province.getCity().add(cityBean);
                    CityListStr.add(caption);
                }
                Log.i("tag2", "RegionId = " + regionId+"-----caption = " + caption);
            }
            if (cursor1 != null && !cursor1.isClosed()) {
                cursor1.close();
            }
            /**
             * 添加城市数据
             */
            options2Items.add(CityListStr);
        }

        for (int i = 0; i < provinceList.size(); i++) {
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            JsonBean province = provinceList.get(i);
            int pro_region = province.getRegion();
            List<JsonBean.CityBean> cityList = province.getCity();
            for (int j = 0; cityList != null && j < cityList.size(); j++) {
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                JsonBean.CityBean city = cityList.get(j);
                int city_region = city.getRegion();
                String s = String.valueOf(city_region);
                String height = s.substring(0, 4);
                Cursor cursor2 = db.rawQuery("select * from region where RegionId like " + "'" + height + "%'", null);
                while (cursor2.moveToNext()) {
                    String caption = cursor2.getString(cursor2.getColumnIndex("Caption"));
                    int regionId = cursor2.getInt(cursor2.getColumnIndex("RegionId"));
                    if (regionId != pro_region && regionId != city_region) {
                        JsonBean.CityBean.CountyBean countyBean = new JsonBean.CityBean.CountyBean(caption, regionId);

                        List<JsonBean.CityBean.CountyBean> countyList = city.getCounty();
                        if (countyList == null) {
                            // TODO: 2017/6/23 少了一个
                            city.setCounty(new ArrayList<JsonBean.CityBean.CountyBean>());
                        }
                        City_AreaList.add(caption);//添加该城市所有地区数据
                        city.getCounty().add(countyBean);

                    }
                }
                if (cursor2 != null && !cursor2.isClosed()) {
                    cursor2.close();
                }
                if (city.getCounty() == null
                        || city.getCounty().isEmpty()) {
                    City_AreaList.add("");
                } else {
                    for (int d = 0; d < city.getCounty().size(); d++) {//该城市对应地区所有数据
                        String AreaName = city.getCounty().get(d).getName();
                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);

        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
        Log.i("tag", count + "------------------------------------------");
    }

    private void initView() {
        findViewById(R.id.btn_data).setOnClickListener(this);
        findViewById(R.id.btn_show).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_data:
                mHandler.sendEmptyMessage(MSG_LOAD_DATA);
                break;
            case R.id.btn_show:
                if (isLoaded) {
                    ShowPickerView();
                } else {
                    Toast.makeText(JsonDataActivity.this, "数据暂未解析成功，请等待", Toast.LENGTH_SHORT).show();
                }

                break;

        }

    }


    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);

                Toast.makeText(JsonDataActivity.this, tx, Toast.LENGTH_SHORT).show();
            }


        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            List<JsonBean.CityBean> city = jsonBean.get(i).getCity();
            for (int c = 0; c < city.size(); c++) {//遍历该省份的所有城市
                JsonBean.CityBean cityBean = city.get(c);
                String CityName = cityBean.getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                List<JsonBean.CityBean.CountyBean> county = cityBean.getCounty();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (county == null
                        || county.isEmpty()) {
                    City_AreaList.add("");
                } else {
                    for (int d = 0; d < county.size(); d++) {//该城市对应地区所有数据
                        String AreaName = county.get(d).getName();
                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }
}
